package mya.mes.mdc.internal.ui;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import freemarker.core.ParseException;
import freemarker.log.Logger;
import freemarker.template.Configuration;
import freemarker.template.MalformedTemplateNameException;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import freemarker.template.TemplateNotFoundException;
import sun.misc.BASE64Encoder;

import javax.ws.rs.core.Response;

public class ExportMyWord {


    private static Logger log = Logger.getLogger(ExportMyWord.class.toString());
    private static Configuration config = new Configuration(Configuration.VERSION_2_3_28);

    public ExportMyWord() {

    }

    /**
     * FreeMarker生成Word
     *
     * @param dataMap      数据
     * @param templateName 目标名
     * @param saveFilePath 保存文件路径的全路径名（路径+文件名）
     */
    public static File createWord(Map<String, String> dataMap, String templateName, String saveFilePath) throws IOException {
        //加载模板(路径)数据
//        config.setClassForTemplateLoading(this.getClass(), "/");
        config.setDefaultEncoding("UTF-8");
        config.setDirectoryForTemplateLoading(new File("E:\\idea_project\\mes-mdc-parent_0619_new\\mes-mdc-internal\\src\\main\\java\\mya\\mes\\mdc\\internal\\ui"));
        //设置异常处理器 这样的话 即使没有属性也不会出错 如：${list.name}...不会报错
        config.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
        Template template = null;
        if (templateName.endsWith(".ftl")) {
            templateName = templateName.substring(0, templateName.indexOf(".ftl"));
        }
        try {
            template = config.getTemplate(templateName + ".ftl","UTF-8");
        } catch (TemplateNotFoundException e) {
            log.error("模板文件未找到", e);
            e.printStackTrace();
        } catch (MalformedTemplateNameException e) {
            log.error("模板类型不正确", e);
            e.printStackTrace();
        } catch (ParseException e) {
            log.error("解析模板出错，请检查模板格式", e);
            e.printStackTrace();
        } catch (IOException e) {
            log.error("IO读取失败", e);
            e.printStackTrace();
        }
        File outFile = new File(saveFilePath);
        if (!outFile.getParentFile().exists()) {
            outFile.getParentFile().mkdirs();
        }
        Writer out = null;
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(outFile);
        } catch (FileNotFoundException e) {
            log.error("输出文件时未找到文件", e);
            e.printStackTrace();
        }
        out = new BufferedWriter(new OutputStreamWriter(fos,"UTF-8"));
        //将模板中的预先的代码替换为数据
        try {
            template.process(dataMap, out);
        } catch (TemplateException e) {
            log.error("填充模板时异常", e);
            e.printStackTrace();
        } catch (IOException e) {
            log.error("IO读取时异常", e);
            e.printStackTrace();
        }finally {
            if(out!=null){
                try {
                    out.flush();
                    out.close();
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }
        }
        log.info("由模板文件：" + templateName + ".ftl" + " 生成文件 ：" + saveFilePath + " 成功！！");
        try {
//            out.close();//web项目不可关闭
        } catch (Exception e) {
            log.error("关闭Write对象出错", e);
            e.printStackTrace();
        }
        return outFile;
    }

    /**
     * 获得图片的Base64编码
     *
     * @param imgFile
     * @return
     * @Author Huang Xiaocong 2018年12月15日 下午10:15:10
     */
    public String getImageStr(String imgFile) {
        InputStream in = null;
        byte[] data = null;
        try {
            in = new FileInputStream(imgFile);
        } catch (FileNotFoundException e) {
            log.error("加载图片未找到", e);
            e.printStackTrace();
        }
        try {
            data = new byte[in.available()];
            //注：FileInputStream.available()方法可以从输入流中阻断由下一个方法调用这个输入流中读取的剩余字节数
            in.read(data);
            in.close();
        } catch (IOException e) {
            log.error("IO操作图片错误", e);
            e.printStackTrace();
        }
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);

    }

    public static void main(String[] args) throws IOException {
        ExportMyWord emw = new ExportMyWord();
        Map<String, String> dataMap = new HashMap<String, String>();
        dataMap.put("line", "4号线");
        dataMap.put("l4_z1_c_2", "20");
        dataMap.put("l4_z1_c_3", "20");
        dataMap.put("l4_z1_c_4", "20");
        dataMap.put("l4_z1_c_5", "20");
        dataMap.put("l4_z1_c_6", "20");
        dataMap.put("l4_z1_c_7", "20");
        dataMap.put("l4_z2_c_1", "20");
        dataMap.put("l4_z2_c_2", "20");
        dataMap.put("l4_z2_c_3", "20");
        dataMap.put("l4_z2_c_4", "20");
        dataMap.put("l4_z2_c_5", "20");
        dataMap.put("l4_z2_c_6", "20");
        dataMap.put("l4_z3_c_1", "20");
        dataMap.put("l4_z3_c_2", "20");
        dataMap.put("l4_z3_c_3", "20");
        dataMap.put("l4_z3_c_4", "20");
        dataMap.put("l4_z3_c_5", "20");
        dataMap.put("l4_z3_c_6", "20");
        dataMap.put("l4_z4_c_1", "20");
        dataMap.put("l4_z4_c_2", "20");
//        File file = emw.createWord(dataMap, "module.ftl", "E:/Line3.doc");
        File file = emw.createWord(dataMap, "line4_.ftl", "E:/Line4.xls");
        System.out.println(file.getName());
    }
}